<?php
namespace app\Admin\controller;
use think\Controller;
use think\Db;
use think\Session;
use think\Cache;
use think\Request;
use think\Loader;
use think\Validate;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
//定义常量
define('PATH', 'D:/wwwroot/apizgyejynet_2bacea/web/public');

class Admin extends Base
{
    /**
    **  后台的登陆页面
    **/
    public function login()
    {

        return $this->fetch();
    }

    /**
    *   登陆的操作
    **/
    public function doLogin()
    {
        $data = input('post.');
        $passwd = md5(input('post.passwd'));
        //查询用户
        $user = Db('adminuser')->where('username',$data['username'])->find();
        //判断验证码是否存在
        if(captcha_check($data['code'])){
            if($user){
            //判断密码是否正确
                if($user['passwd'] == $passwd){
                    Session::set('adminUserId',$user['id']);
                    echo 1;die;
                }else{
                    echo 2;die;
                }
            }else{
                echo 0;die;
            }
        }else{
            echo 3;die;
        }
        
    }
    /**
    **退出登陆
    **/
    public function logout()
    {
        Session::set('adminUserId',null);
        Session::set('adminUser',null);
        $adminUserId = Session::get('adminUserId');
        $adminUser = Session::get('adminUser');
        if( empty($adminUserId) && empty($adminUser) ){
           return $this->success('退出登陆成功','admin/admin/login'); 
       }else{
            return $this->error('退出登陆失败');
       }
        
    }
	/**
	**	后台首页
	**/
    public function index()
    {
        $adminUser  = Db('adminuser')->where('id',Session::get('adminUserId'))->find();
        Session::set('adminUser',$adminUser['username']);
        //当前用户明
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
        // 渲染模板输出 并赋值模板变量
        return $this->fetch(); 
  
		
    }


/**********************管理员操作***********************************/
    /**
    * 管理员的添加页面
    ***/
    public function adminUserAdd()
    {
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
        //
        $authRule = Db('auth_rule')->select();
        $this->assign('authRule',$authRule);
        return $this->fetch();
    }

    /**
    ** 添加管理员操作
    **/
    public function doAdminUserAdd()
    {
        $post = input('post.');
        if(!empty($post['id'])){
            $nopower = implode(',',$post['id']);
        }
        //
        $username = input('post.username');
        $password = input('post.password');
        $data['username'] = isset($username) ? $username : '';
        $data['passwd'] = isset($password) ? md5($password) : '';
        $data['nopower'] = isset($nopower) ? $nopower : '';

        if(empty($username)){
            return $this->error('用户名不能为空');
        }
        if(empty($password)){
            return $this->error('密码不能为空');
        }
        if(!empty($username) && !empty($password)){
            $res = Db('adminuser')->insert($data);
            if($res == 1){
                return $this->success('添加成功','admin/admin/adminuserList');
            }else{
                return $this->error('添加失败'); 
            }
        }

    }

    /**
    ** 管理员的显示列表
    **/
    public function adminUserList()
    {
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
        $adminUsers = Db('adminuser')->paginate(10);
        $this->assign('adminUsers',$adminUsers);
        return $this->fetch();
    }

    /*
    ** 管理员的修改操作
    **/
    public function adminUserEdit()
    {

    }

    /**
    * 管理员的删除操作
    **/
    public function adminUserDelete()
    {
        $id = input('get.id');
        $id = isset($id) ? $id : '';
        if(!empty($id)){
            $res = Db('adminuser')
                    ->where('id',$id)
                    ->delete();
            if($res == 1){
                return $this->success('删除成功');
            }else{
                return $this->error('删除失败');
            }
        }else{
            return $this->error('删除失败'); 
        }
        
    }

    /**
    ** 修改密码操作
    **/
    public function passwordEdit()
    {
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
        return $this->fetch();
    }
    /**
    ** 修改密码操作
    **/
    public function doPasswordEdit()
    {
        $oldPassword = input('post.oldPassword');
        $newPassword = input('post.newPassword');
        $rePassword = input('post.rePassword');
        
        if(!empty($oldPassword) && !empty($newPassword) && !empty($rePassword)){
            $id = Session::get('adminUserId');
            $adminUser = Db('adminuser')->where('id',$id)->find(); 
            if($adminUser['passwd'] == md5($oldPassword)){
                if($newPassword == $rePassword){
                    $data['passwd'] = MD5($newPassword);
                    $res = Db('adminuser')->where('id',$id)->update($data);
                    if($res == 1){
                        Session::set('adminUserId',null);
                        Session::set('adminUser',null);
                        return $this->success('修改成功','admin/admin/login');
                    }else{
                        return $this->error('修改失败');
                    }
                }else{
                    return  $this->error('两次密码不一致');
                }
            }else{
                 return  $this->error('原密码不正确');
            }
        }else{
            if(empty($oldPassword)){
                return  $this->error('原密码不能为空');
            }
            if(empty($newPassword)){
                return $this->error('新密码不能为空');
            }
            if(empty($rePassword)){
                return $this->error('重复密码不能为空');
            }
        }
        
    }


/**********************视频分类操作***********************************/
    /**
    *   视频分类的添加页面
    **/
    public function cateAdd()
    {
        //当前用户明
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
        //将分类信息读出来
        $cates = $this->getAllCates();
        //模板变量赋值
        $this->assign('cates',$cates);
        return $this->fetch();
 

    }
    /**
    *  分类的添加操作
    **/
     public function doCateAdd()
     {
       
                //获取数据
                $name = input('post.name');
                $pid = input('post.pid');
                $data['name'] = $name;
                //判断的当前分类是否是顶级分类
                if( $pid == "0"){
                    $data['pid'] = '0';
                    $data['path'] = '0';
                }else{
                    //读取腹肌分类的信息
                    $info = Db::table('cates')->where('id','=',$pid)->find();
                    //拼接当前分类的path字段字符串
                    $data['pid'] = $info['id'];
                    $data['path'] = $info['path'].','.$info['id'];
                }
                //插入数据库
                $res = Db::table('cates')->insert($data);
                if($res == 1){
                    $cates = Db('cates')->where('name',$name)->find();
                    $cate['paths'] = $cates['path'].','.$cates['id'];
                    $res = Db::table('cates')->where('id',$cates['id'])->update($cate);
                    return $this->success('添加成功','admin/cateList');
                }else{
                    return $this->error('添加失败');
                }
        
     }

    /**
    *   分类列表显示页面
    **/
    public function cateList()
    {
 
            //当前用户明
            $adminUser = Session::get('adminUser');
            $this->assign('adminUser',$adminUser);
            //创建缓存的键名
            // $request = Request::instance();
            // $key = $request->url(true);
            // //判断是否有缓存数据
            // if(!Cache::get($key)){
                //查询数据
            $name = input('get.name');
            if(empty( $name )){
                $cates = Db::table('cates')
                    ->field('id,pid,name,path')
                    ->order('id asc')
                    ->paginate(10);            
            }
            if(!empty($name)){
                $cates = Db('cates')
                    ->where('name','like','%'.$name.'%')
                    ->paginate(10);
            }
                
                //foreach
            //     $cates = $this->formatCateInfo($cates);
            //     //设置缓存
            //     Cache::set($key,$cates,3600);
            // }else{
            //     //获取缓存
            //     $cates = Cache::get($key);
            // }
            $this->assign('cates',$cates);
            return $this->fetch();

    }

    /**
    *   分类的修改页面
    **/
    public function cateEdit()
    {
        //当前用户明
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
        //获取当前的分类信息
        $info = Db::table('cates')->where('id','=',input('get.id'))->find();
        //
        $cates = $this->getAllCates();
        //
        $this->assign('info',$info);
        $this->assign('cates',$cates);
        return $this->fetch();

    }

    /**
    *   分类的修改操作
    **/
    public function doCateEdit()
    {

        //获取信息
        $name = input('post.name');
        $data['name'] = $name;
        //修改数据
        $res = Db::table('cates')->where('id','=',input('post.id'))->update($data);
        //判断
        // var_dump($res);die;
        if($res == 1){
            return $this->success('修改成功','admin/cateList');
        }else{
            return $this->error('修改失败');
        }

    }

    /**
    *分类的删除操作
    **/
    public function cateDelete()
    {
        $id = input('get.id');
        $res = Db::table('cates')->where('id','=',input('get.id'))->delete();
        if($res == 1){
            return $this->success('删除成功','admin/cateList');
        }else{
            return $this->error('删除失败');
        }
    }

     /**
     * 获取当前所有的分类信息
     */
    private function getAllCates()
    {
        //读取所有的分类信息
        //查询数据
        $cates = Db::table('cates')
            ->field('id,name,path')
            ->order('paths asc')
            ->select();

        //获取foreach
        $cates = $this->formatCateInfo($cates);
        //返回结果
        return $cates;
    }

   /**
     * 处理数据 格式化显示分类信息
     */
    private function formatCateInfo($cates)
    {
        //修改缩进样式
         foreach($cates as $k=>$v) {
            //判断当前的分类的等级
            $arr = explode(',', $v['path']);
            $level = count($arr) - 1;
            //修改分类中的名称  |-----
            $cates[$k]['name'] = str_repeat('|-----', $level).$v['name'];

        }
        return $cates;
    }
/**********************视频操作***********************************/

    /**
    *	视频的添加页面
    **/
    public function videoAdd()
    {
        
        //当前用户明
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
    	// $cates = Db::table('cates')->select();
        $cates = $this->getAllCates();
        $this->assign('cates',$cates);
    	return $this->fetch();

    }

    /**
    *	视频的上传操作
    **/
    public function doVideoAdd()
    {
        // vendor('QiNiu.autoload');
        // $file = request()->file('video');
        // // 需要填写你的 Access Key 和 Secret Key
        // $accessKey = config('ACCESSKEY');
        // $secretKey = config('SECRETKEY');
        // // 构建鉴权对象
        // $auth = new Auth($accessKey, $secretKey);
        // // 要上传的空间
        // $bucket = config('BUCKET');
        // // 生成上传 Token
        // $token = $auth->uploadToken($bucket);
        // // 要上传文件的本地路径
        // $filePath = $file->getRealPath();
        // $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
     
        // // 上传到七牛后保存的文件名
        // $key = substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;
        // // 初始化 UploadManager 对象并进行文件的上传
        // $uploadMgr = new UploadManager();
        // // 调用 UploadManager 的 putFile 方法进行文件的上传
        // list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        // echo "\n====> putFile result: \n";
        // if ($err !== null) {
        //     // var_dump($err);
        //     return $this->error('添加失败');
        // } else {
        //      // var_dump($ret);
        //     $videoUrl = config('VIDEOURL');
        //     $data['video_url'] = $videoUrl.$ret['key'];
        // }

        //接受图片和视频
        $video_zip = request()->file("video_zip");
        //
        $video = request()->file("video");     
        //判断是否上传图片
        if(!empty($video_zip)){
            $video_zip = $this->uploadimg($video_zip);
            $data['video_zip'] = $video_zip;
        }
        //判断是否上传视频
        if(!empty($video)){
            $video = $this->uploadvideo($video);
            $data['video_url'] = $video;
        }
        
        $data['video_name'] = input('post.video_name');
        $data['video_describe'] = input('post.video_describe');
               
        $data['video_addtime'] = time();
        //浏览数量
        $data['see_num'] = 0;
        //评论数量
        $data['evaluate_num'] =0;
        //收藏数量
        $data['collect_num'] =0;
        //分类id
        $data['cate_id'] = input('post.cate_id');
        $video_price = input('post.video_price');

        $data['video_price'] = $video_price;
        //判断是否付费
    	// if(empty($video_price)){
     //        $data['video_style'] = '1';
     //    }else{
     //        $data['video_style'] = '2';
     //    }

        $video_jifen = input('post.video_jifen');
        $data['video_jifen'] = $video_jifen;
        // if(empty($video_jifen)){
        //     $data['video_style'] = '1';
        // }else{
        //     $data['video_style'] = '3';
        // }
        $video_style = input('post.video_style');
        if($video_style == 0 || empty($video_style)){
            return $this->error('视频类型参数不合法');
        } 
        $data['video_style'] = $video_style;
        //
    	$res = Db('video')->insert($data);
    	if($res == 1){
    		return $this->success('上传成功','admin/videoList');
    	}else{
    		return $this->error('上传失败');
    	}
    } 
    /**
    **  视频上传操作
    **/
    private function uploadvideo($video)
    {
        // 获取表单上传文件 例如上传了001.jpg
        // $img = request()->file('video');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $imginfo = $video->move(ROOT_PATH . 'public' . DS . 'uploads'. DS .'video'. DS .'video');
        if($imginfo){
            return $imgurl = "/uploads/video/video/20".date("ymd",time())."/".$imginfo->getBasename();
        }else{
            // 上传失败获取错误信息
            return  $video->getError();
        }   
    }

    /**
    *   图片上传操作
    **/
    private function uploadimg($video_zip)
    {
        // 获取表单上传文件 例如上传了001.jpg
        // $img = request()->file('video_zip');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $imginfo = $video_zip->move(ROOT_PATH . 'public' . DS . 'uploads'. DS .'video'. DS .'images');
        //
        if($imginfo){
                return $url = "/uploads/video/images/20".date("ymd",time())."/".$imginfo->getBasename();
        }else{
            // 上传失败获取错误信息
            return  $video_zip->getError();
        }   
    }
      /**
    *   MP3上传操作
    **/
    private function uploadMusic($music)
    {
        // 获取表单上传文件 例如上传了001.jpg
        // $img = request()->file('video_zip');
        // 移动到框架应用根目录/public/uploads/ 目录下
        
        $musicInfo = $music->move(ROOT_PATH . 'public' . DS . 'uploads/video/music');
        if($musicInfo){
                return $url = "/uploads/video/music/20".date("ymd",time())."/".$musicInfo->getBasename();
        }else{
            // 上传失败获取错误信息
            return  $music->getError();
        }   
    }
      /**
    *   文档上传操作
    **/
    private function uploadText($text)
    {
        // 获取表单上传文件 例如上传了001.jpg
        // $img = request()->file('video_zip');
        // 移动到框架应用根目录/public/uploads/ 目录下
        
        $textInfo = $text->move(ROOT_PATH . 'public' . DS . 'uploads/video/text');
        if($textInfo){
                return $url = "/uploads/video/text/20".date("ymd",time())."/".$textInfo->getBasename();
        }else{
            // 上传失败获取错误信息
            return  $text->getError();
        }   
    }
    /**
    *	视频的列表页
    **/
    public function videoList()
    {
                //当前用户明
                $adminUser = Session::get('adminUser');
                $this->assign('adminUser',$adminUser);
            	//创建缓存的键名
                $request = Request::instance();
                $key = $request->url(true);
                
                // //读取视频信息
                // $video = Db::table('video')
                //         ->order('id desc')
                            // if(!empty(input('get.video_name'))){
                //         ->where(function($query){       
                //              $query->where('video_name','like','%'.input('get.video_name').'%');
                //             }
                //             if(!empty(input('get.video_style'))){
                //                $query->where('video_style','=',input('get.video_style')); 
                //             }
                //         })
                //          ->select();
                $video_style = input('get.video_style');
                $video_name = input('get.video_name');
                 if(empty($video_style) && empty($video_name))
                {
                    //判断是否有缓存
                    // if(!Cache::get($key)){
                         $video = Db::table('video')
                                ->order('id desc')                               
                                ->paginate(10);
                        //设置缓存
                    //     Cache::set($key,$video,360);
                    // }else{
                    //     //获取缓存
                    //     $video = Cache::get($key);
                    // }
                }
                //
                if(!empty($video_name)){
                    $video = Db::table('video')
                            ->order('id desc')
                            ->where('video_name','like','%'.$video_name.'%')
                            ->paginate(10);
                }
                //

                if(!empty($video_style)){
                    $video = Db::table('video')
                            ->order('id desc')
                            ->where('video_style','=', $video_style)
                            ->paginate(10);
                }
                //
                if(!empty($video_style) && !empty($video_name))
                {
                     $video = Db::table('video')
                            ->order('id desc')
                            ->where(function($query){
                                    $query->where('video_style','=',$video_style);
                                    $query->where('video_name','like','%'.$video_name.'%');
                            })                               
                        ->paginate(10);
                }       
                $this->assign('video',$video);
            	return $this->fetch();

    }
    /**
    **视频的修改页面
    **/
    public function videoEdit()
    {
        //当前用户明
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
        //
        $video = Db::table('video')->where('id','=',input('get.id'))->find();
        //
        $this->assign('video',$video);
        //
        return $this->fetch();
    }
    
    /**
    *   视频的修改操作
    **/
    public function doVideoEdit()
    {
        $videoinfo = Db::table('video')->where('id','=',input('post.id'))->find();
         //接受图片和视频
        $video_zip = request()->file("video_zip");
        $video = request()->file("video");
       

        //判断是否修改图片
        if(!empty($video_zip)){
            //判断文件是否存在
            if(file_exists(PATH.$videoinfo['video_zip']) && is_file(PATH.$videoinfo['video_zip'])){
                //
                $result = unlink(PATH.$videoinfo['video_zip']);
                if(!$result){
                    return $this->error('修改失败');
                }
            } 
            //上传新图片
            $video_zip = $this->uploadimg($video_zip); 
            $data['video_zip'] = $video_zip;         
        }
        
        //判断是否上传视频
        if(!empty($video)){
            //判断文件是否存在
            if(file_exists(PATH.$videoinfo['video_url']) && is_file(PATH.$videoinfo['video_url'])){
                //删除原来的视频
                $result = unlink(PATH.$videoinfo['video_url']);
                if(!$result){
                    return $this->error('修改失败');
                }
            }
            //上传新视频
            $video = $this->uploadvideo($video);
            $data['video_url'] = $video;             
        }
        
        
        //
        $video_name = input('post.video_name');
        if(!empty($video_name)){
            $data['video_name'] = $video_name;
        }
        //
        $video_describe = input('post.video_describe');
        if(!empty($video_describe)){
            $data['video_describe'] = $video_describe;
        }
        //
        $video_price = input('post.video_price');
        if(!empty($video_price)){
            $data['video_price'] = $video_price;
        } 
        //
        $video_jifen = input('post.video_jifen');
         if(!empty($video_jifen)){
            $data['video_jifen'] = $video_jifen;
        }       
        //        
        $data['video_addtime'] = time();
        //判断是否付费
        $video_style = input('post.video_style');
        if($video_style == 1){
            $data['video_style'] = '1';
            $data['video_price'] = '';
            $data['video_jifen'] = '';
        }elseif($video_style == 2){
            $data['video_style'] = '2';
            $data['video_jifen'] = '';
        }elseif($video_style == 3){
            $data['video_style'] = '3';
            $data['video_price'] = '';
        }
        //
        //修改
        $res = Db::table('video')->where('id','=',input('post.id'))->update($data);
        if($res == 1){
            return $this->success('修改成功','admin/videoList');
        }else{
            return $this->error('修改失败');
        }
    }

    /**
    *   视频的删除操作
    **/
    public function videoDelete()
    {
        $id = input('get.id');
        $videoinfo = Db::table('video')->where('id','=',input('get.id'))->find();
        //判断视频是否存在
        if(file_exists(PATH.$videoinfo['video_url']) && is_file(PATH.$videoinfo['video_url'])){
                //删除原有文件
               $delViode = unlink(PATH.$videoinfo['video_url']);
        }
        //判断图片是否存在
        if(file_exists(PATH.$videoinfo['video_zip']) && is_file(PATH.$videoinfo['video_zip'])){
                //删除原有文件
                $delImg = unlink(PATH.$videoinfo['video_zip']);
        }
        
        //判断
            $res = Db::table('video')->where('id','=',input('get.id'))->delete();
            if($res == 1){
                 return $this->success('删除成功','admin/videoList');
            }else{
                 return $this->error('删除失败');
            }         
    }
    /**
    ** mp3和文档添加页面
    **/
    public function Mp3TextAdd()
    {
        //当前用户明
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
        $cates = $this->getAllCates();
        $this->assign('cates',$cates);
        return $this->fetch();

    }
    /**
    **mp3和文档添加操作
    **/
    public function doMp3TextAdd()
    {
        $data['music_name'] = input('post.music_name');
        $data['text_name'] = input('post.text_name');
        $data['music_price'] = input('post.music_price');     
        $data['text_price'] = input('post.text_price');
        $data['music_jifen'] = input('post.music_jifen');
        $data['text_jifen'] = input('post.text_jifen');
        //
        $music_style = input('post.music_style');
        if($music_style == 0 || empty($music_style)){
            return $this->error('mp3类型参数不合法');
        } 
        $data['music_style'] = $music_style;
        //
        $text_style = input('post.text_style');
        if($text_style == 0 || empty($text_style)){
            return $this->error('mp3类型参数不合法');
        } 
        $data['text_style'] = $text_style;
        //
        $music = request()->file("music");
        $text = request()->file('text');
         //判断是否上传mp3
        if(!empty($music)){
            $music = $this->uploadMusic($music);
            $data['music'] = $music;
        }
        //判断是否上传mp3
        if(!empty($text)){
            $text = $this->uploadText($text);
            $data['text'] = $text;
        }
        $data['cateId'] = input('post.cate_id');
        if($data['cateId']){
            $cates = Db('cates')->where('id',$data['cateId'])->find();
            $data['cate_name'] = $cates['name'];
        }       
        $res = Db('mp3text')->insert($data);
        if($res == 1){
            return $this->success('上传成功','admin/mp3TextList');
        }else{
            return $this->error('上传失败');
        }

    }

    /**
    **mp3和文档列表页
    **/
    public function mp3textlist()
    {
        //当前用户明
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
        $mp3Text = Db::table('mp3text')
                    ->order('id desc')
                    ->paginate(10); 
        
        // var_dump($mp3Text );die;
        // foreach($mp3Text as $k => $v){
        //   $mp3Text[$k]['cateId'] = $v['cateId'];
                
        // }                    
        $this->assign('mp3Text',$mp3Text);
        return $this->fetch();               
    }
    /**
    ** 修改页面
    **/
    public function mp3TextEdit()
    {
        //当前用户明
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
        $cates = $this->getAllCates();
        $this->assign('cates',$cates);
         $mp3Text = Db::table('mp3text')->where('id','=',input('get.id'))->find();
        //
        $this->assign('mp3Text',$mp3Text);

        return $this->fetch();
    }
    /**
    ** 修改操作
    **/
    public function doMp3TextEdit()
    {
        //判断是否修改mp3的参数
        $musicName = input('post.music_name');
        if(!empty($musicName)){
            $data['music_name'] = $musicName;
        }
        $musicPrice = input('post.music_price');
        if(!empty($musicPrice)){
            $data['music_price'] = $musicPrice;
        }
        //
        $musicStyle = input('post.music_style');
        if(!empty($musicStyle)){
                if($musicStyle == 1){
                    $data['music_style'] = '1';
                    $data['music_price'] = '';
                    $data['music_jifen'] = '';
                }elseif($musicStyle == 2){
                    $data['music_style'] = '2';
                    $data['music_jifen'] = '';
                }elseif($musicStyle == 3){
                    $data['music_style'] = '3';
                    $data['music_price'] = '';
                }
        }
         $musicJifen = input('post.music_jifen');
        if(!empty($musicJifen)){
            $data['music_jifen'] = $musicJifen;
        }
        //判断是否修改text的参数
        $textName = input('post.text_name');
        if(!empty($textName)){
            $data['text_name'] = $textName;
        }
        $textPrice = input('post.text_price');
        if(!empty($textPrice)){
            $data['text_price'] = $textPrice;
        }
        $textStyle = input('post.text_style');
        if(!empty($textStyle)){
                if($textStyle == 1){
                    $data['text_style'] = '1';
                    $data['text_price'] = '';
                    $data['text_jifen'] = '';
                }elseif($textStyle == 2){
                    $data['text_style'] = '2';
                    $data['text_jifen'] = '';
                }elseif($textStyle == 3){
                    $data['text_style'] = '3';
                    $data['text_price'] = '';
                }
        }
        $textJifen = input('post.text_jifen');
        if(!empty($textJifen)){
            $data['text_jifen'] = $textJifen;
        }
        //是否改变分类
        $cateId = input('post.cate_id');
        if(!empty($cateId)){
            $data['cateId'] = $cateId;
            $cates = Db('cates')->where('id',$cateId)->find();
            $data['cate_name'] = $cates['name'];
        } 
        //
        $music = request()->file("music");
        $text = request()->file('text');
        $mp3text = Db::table('mp3text')->where('id','=',input('post.id'))->find();
          //判断是否上传mp3
        if(!empty($music)){
            //判断文件是否存在
            if(file_exists(PATH.$mp3text['music']) && is_file(PATH.$mp3text['music'])){
                //删除原来的视频
                $result = unlink(PATH.$mp3text['music']);
                if(!$result){
                    return $this->error('修改失败');
                }
            }
            //上传新视频
            $music = $this->uploadMusic($music);
            $data['music'] = $music;             
        }
          //判断是否上传文档
        if(!empty($text)){
            //判断文件是否存在
            if(file_exists(PATH.$mp3text['text']) && is_file(PATH.$mp3text['text'])){
                //删除原来的文档
                $result = unlink(PATH.$mp3text['text']);
                if(!$result){
                    return $this->error('修改失败');
                }
            }
            //上传新文档
            $text = $this->uploadText($text);
            $data['text'] = $text;             
        }
         //修改
        $res = Db::table('mp3text')->where('id','=',input('post.id'))->update($data);
        if($res == 1){
            return $this->success('修改成功','admin/mp3TextList');
        }else{
            return $this->error('修改失败');
        }
    }

    /**
    ** 删除操作
    **/

    public function mp3TextDelete()
    {
        $mp3text = Db::table('mp3text')->where('id','=',input('get.id'))->find();
        //判断mp3是否存在
        if(file_exists(PATH.$mp3text['music']) && is_file(PATH.$mp3text['music'])){
                //删除原有文件
                $delMusic = unlink(PATH.$mp3text['music']);
        }
        //判断文档是否存在
        if(file_exists(PATH.$mp3text['text']) && is_file(PATH.$mp3text['text'])){
                //删除原有文件
                $delText = unlink(PATH.$mp3text['text']);
        }
         //判断
            $res = Db::table('mp3text')->where('id','=',input('get.id'))->delete();
            if($res == 1){
                 return $this->success('删除成功','admin/mp3TextList');
            }else{
                 return $this->error('删除失败');
            }  
    }


/**********************用户管理***********************************/
    /**
    **  用户列表的显示页面
    **/
    public function userList()
    {
                //当前用户明
                $adminUser = Session::get('adminUser');
                $this->assign('adminUser',$adminUser);
                //创建缓存名字
                $request = Request::instance();
                $key = $request->url(true);
                //判断
                $phone = input('get.phone');
                if(empty($phone))
                {   
                    //判断缓存是否存在
                    // if(!Cache::get($key)){
                         $user = Db('users')
                                 
                                 ->paginate(10); 
                       
                    
                }

                if(!empty($phone)){               
                     $user = Db('users')
                           
                            ->where('phone','like','%'.$phone.'%') 
                            ->order('addtime desc')    
                            ->paginate(10);


                }                              
                $this->assign('user',$user);
                return $this->fetch();
    }

    /**
    **  用户的删除操作
    **/
    public function userDelete()
    {
        $id = input('get.id');      
        $user = Db::table('users')->where('id','=',$id)->find();
        // if(file_exists(PATH.$user['image']) && is_file(PATH.$user['image'])){
        //     //删除原来的视频
        //     $result = unlink(PATH.$user['image']);
        // }     
        $result = Db::table('users')->where('id','=',$id)->delete();
        if($result == 1){
            Db::table('payVideo')->where('userid','=',$id)->delete();
            Db::table('collectVideo')->where('userid','=',$id)->delete();
            Db::table('coupon')->where('userid','=',$id)->delete();
			Db::table('userinfo')->where('uid','=',$id)->delete();
            return $this->success('删除成功','admin/userList');
        }else{
            return $this->error('删除失败');
        }
    }

/*****************************活动管理********************************************/
    /**
    **  活动添加页面
    **/
    public function activeAdd()
    {
        //当前用户明
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
        return $this->fetch();

    }
    /**
    **活动的添加操作
    **/
    public function doActiveAdd()
    {
        //接受数据
        $post = input('post.');
        //开始的时间
        $beginTime = input('post.active_begintime1').','.input('post.active_begintime2');
        $beginTime = strtotime($beginTime);
        //结束的时间
        $endTime = input('post.active_endtime1').','.input('post.active_endtime2');
        $endTime = strtotime($endTime);       
        //接受图片信息
        $active_image = request()->file("active_image");
        //判断是否上传图片
        if(!empty($active_image)){
            // 移动到框架应用根目录/public/uploads/ 目录下
            $imginfo = $active_image->move(ROOT_PATH . 'public' . DS . 'uploads/active/images');
            if($imginfo){
                    $active_image = "/uploads/active/images/20".date("ymd",time())."/".$imginfo->getBasename();
            } 
        }
        //
        $data['active_image'] = $active_image;
        $data['active_name'] = $post['active_name'];
        $data['active_begintime'] = $beginTime;
        $data['active_endtime'] = $endTime;
        $data['active_adress'] = $post['active_adress'];
        $data['active_content'] = $post['active_content'];
        $data['active_link'] = $post['active_link'];
        //插入数据
        $res = Db('active')->insert($data);
        if($res == 1){
            return $this->success('添加成功','admin/activeList');
        }else{
            return $this->error('添加失败');
        }
    }

    /**
    * 活动的列表显示页面
    **/
    public function activeList()
    {
                //当前用户明
                $adminUser = Session::get('adminUser');
                $this->assign('adminUser',$adminUser);
                //设置缓存的key值
                $request = Request::instance();
                $key = $request->url(true);
                $active_name = input('get.active_name');
                if(empty($active_name)){
                     //判断缓存是否存在
                    // if(!Cache::get($key)){
                        $active = Db('active')
                                    ->order('id desc') 
                                    ->paginate(10);
                        //设置缓存
                    //     Cache::set($key,$active,3600);
                    // }else{
                    //     //读取缓存
                    //     $active = Cache::get($key);
                    // }             
                }elseif(!empty($active_name)){
                    $active = Db('active')
                            ->order('id desc')
                            ->where(function($query){
                                $query->where('active_name','like','%'.input('get.active_name').'%');
                            })
                            ->paginate(10);
                }
                //      
                $this->assign('active',$active);
                return $this->fetch();

    }

    /**
    *   活动的修改页面
    **/
    public function activeEdit()
    {
         //当前用户明
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);       
        $active = Db('active')->where('id',input('get.id'))->find();
        //
        $this->assign('active',$active);
        return $this->fetch();

    }

    /**
    *   活动的修改操作
    **/
    public function doActiveEdit()
    {
        //判断图片是否修改
        $activeinfo = Db('active')->where('id',input('post.id'))->find();   
        $active_image = request()->file("active_image");
        //
        if(!empty($active_image)){
            //判断文件是否存在
            if(file_exists(PATH.$activeinfo['active_image']) && is_file(PATH.$activeinfo['active_image'])){
                //
                $result = unlink(PATH.$activeinfo['active_image']);
                if(!$result){
                    return $this->error('修改失败');
                }
            }
            // 移动到框架应用根目录/public/uploads/ 目录下
            $imginfo = $active_image->move(ROOT_PATH . 'public' . DS . 'uploads/active/images');
            if($imginfo){
                $active_image = "/uploads/active/images/20".date("ymd",time())."/".$imginfo->getBasename();
                //
                $data['active_image'] = $active_image;
            }            
        } 
        //判断是否修改时间
        $active_begintime1 = input('post.active_begintime1');
        $active_begintime2 = input('post.active_begintime2');
        if(!empty($active_begintime1) && !empty($active_begintime2))
        {
            //开始的时间
            $beginTime = $active_begintime1.','.$active_begintime2;
            $beginTime = strtotime($beginTime);
            $data['active_begintime'] = $beginTime;
        }
        $active_endtime1 = input('post.active_endtime1');
        $active_endtime2 = input('post.active_endtime2');
        if(!empty($active_endtime1) && !empty($active_endtime2))
        {
            //结束的时间
            $endTime = $active_endtime1.','.$active_endtime2;
            $endTime = strtotime($endTime); 
            $data['active_endtime'] = $endTime;
        }  
        $active_name = input('post.active_name');
        if(!empty($active_name)){
            $data['active_name'] = $active_name;
        } 
        $active_adress =  input('post.active_adress');
        if(!empty($active_adress)){
            $data['active_adress'] = $active_adress;
        }
        $active_content = input('post.active_content');
        if(!empty($active_content)){
            $data['active_content'] = $active_content ;
        }      
        //修改 
        $res = Db('active')->where('id',input('post.id'))->update($data);
        //判断
        if($res == 1){
            return $this->success('修改成功','admin/activeList');
        }else{
            return $this->error('修改失败');
        }       
    }

    /**
    *   活动的删除操作
    **/
    public function activeDelete()
    {
        $activeinfo = Db('active')->where('id',input('get.id'))->find();
        if(file_exists(PATH.$activeinfo['active_image']) && is_file(PATH.$activeinfo['active_image'])){
            //删除原来的图片
            $result = unlink(PATH.$activeinfo['active_image']);
        }     
        $result = Db('active')->where('id',input('get.id'))->delete();
        if($result == 1){
            return $this->success('删除成功','admin/activeList');
        }else{
            return $this->error('删除失败');
        }

    }
    /**
    **  报名表
    **/
    public function activeUserList()
    {

        $activeUser = Db('active_user')->order('id desc')->paginate(10);
        //当前用户明
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser); 
        $this->assign('activeUser',$activeUser);
        return $this->fetch();

    }
    /**
    *   活动报名列表的删除
    **/
    public function activeUserDelete()
    {
        //当前用户明
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
        $result = Db('active_user')->where('id',input('get.id'))->delete();
        if($result == 1){
            return $this->success('删除成功','admin/activeUserList');
        }else{
            return $this->error('删除失败');
        }
    }


    /**
    **  生成单个视频二维码
    **/
    public function videoQrcode()
    {
        $id = input('get.id');
        if($id) {  
            $videoUrl =  'http://api.zgyejy.net/index.php/admin/admin/videoCode?id='.$id;     
            //生成当前的二维码
            $qrCode = new \Endroid\QrCode\QrCode();       
            //想显示在二维码中的文字内容，这里设置了一个查看文章的地址
            // $url = url('admin/admin/videoCode/'.$id,'',true,true);
            $url = $videoUrl;
            $qrCode->setText($url)
                ->setSize(300)
                ->setPadding(10)
                ->setErrorCorrection('high')
                ->setForegroundColor(array('r' => 0, 'g' => 0, 'b' => 0, 'a' => 0))
                ->setBackgroundColor(array('r' => 255, 'g' => 255, 'b' => 255, 'a' => 0))
                ->setLabel('')
                ->setLabelFontSize(16)
                ->setImageType(\Endroid\QrCode\QrCode::IMAGE_TYPE_PNG);
             $qrCode->render();
        }
    }
    /**
    **  查询视频
    **/
    public function videoCode()
    {
        $id = input('get.id');
        if($id){
            $video = Db('video')->where('id',$id)->find();
            return self::json(200,'视频返回成功',$video);
        }else{
            return self::json(401,'分类数据不合法','null');
        }
        
    }

    /**
    *   生成多个视频的二维码
    **/
    public function videoQrcodes()
    {
        $id = input('get.id');
        if($id) {        
            //生成当前的二维码
            $qrCode = new \Endroid\QrCode\QrCode();       
            //想显示在二维码中的文字内容，这里设置了一个查看文章的地址
            $url = 'http://api.zgyejy.net/index.php/admin/admin/videoCates?id='.$id;
            $qrCode->setText($url)
                ->setSize(300)
                ->setPadding(10)
                ->setErrorCorrection('high')
                ->setForegroundColor(array('r' => 0, 'g' => 0, 'b' => 0, 'a' => 0))
                ->setBackgroundColor(array('r' => 255, 'g' => 255, 'b' => 255, 'a' => 0))
                ->setLabel('')
                ->setLabelFontSize(16)
                ->setImageType(\Endroid\QrCode\QrCode::IMAGE_TYPE_PNG);
             $qrCode->render();
        }
    }

    public function videoCates()
    {
        $id = input('get.id');
        if($id){
            $cate = Db('cates')->where('id',$id)->find();
            if($cate['pid'] == 0){
                $cates = Db('cates')->where('pid',$id)->select();
                if($cates){
                    return self::json(200,'分类返回成功',$cates);
                }else{
                    return self::json(400,'暂无下级分类',$cates);
                }
               
            }else{
                $videos['video'] = Db('video')->where('cate_id',$id)->select();
                $videos['mp3text'] = Db('mp3text')->where('cateId',$id)->select();
                if($videos){
                    return self::json(200,'视频返回成功',$videos);
                }else{
                    return self::json(400,'暂无视频',$videos);
                }
                
            }         
            
        }else{
            return self::json(401,'分类数据不合法','null');
        }
        
        
    }

    public static function json($code,$message = '', $data = array())
    {
        //判断状态码是否正确
        if(!is_numeric($code)){
            return '';
        }
        //拼接数组
        $result = array(
            'code'=>$code,
            'message'=>$message,
            'data'=>$data
        );
        //转换成json格式
        echo json_encode($result);
    }

    /**
    * 评论列表显示
    **/
    public function commentList()
    {
        //当前用户明
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
        //设置缓存的key值
        $request = Request::instance();
        $key = $request->url(true);
        // var_dump(input('get.activeName'));die;
        $activeName = input('get.activeName');
        if(empty($activeName)){ 
             //判断缓存是否存在
            // if(!Cache::get($key)){
                $comment = Db('comment')
                    ->order('addtime desc')
                    ->order('status desc')
                    ->paginate(10);
                //设置缓存
            //     Cache::set($key,$active,3600);
            // }else{
            //     //读取缓存
            //     $active = Cache::get($key);
            // }             
        }elseif(!empty($activeName)){
            $comment = Db('comment')
                    ->order('addtime desc')
                    ->order('status desc')
                    ->where(function($query){
                        $query->where('videoName','like','%'.input('get.videoName').'%');
                    })
                    ->paginate(10);
        }
        
        $this->assign('comment',$comment);
        return $this->fetch();

    }
    /**
    **评论加精操作
    **/
    public function commentAjax()
    {
        $get = input('get.');
        $data['status'] = 1;
        //修改状态
        $res = Db('comment')->where('id',$get['id'])->update($data);
        if($res == 1){
            echo 1;die;
        }else{
            echo 0;die;
        }
    }
    /***
    **评论的删除操作
    **/
    public function commentDelete()
    {
        $id = input('get.id');
        $res  = Db('comment')->where('id',$id)->delete();
        if($res == 1){
            return $this->success('删除成功','admin/commentList');
        }else{
            return $this->error('删除失败','admin/commentList');
        }
    }




    /**
    ** 关于积分的管理
    **/


    /**
    **  积分的规则设置页面
    **/
    public function integralAdd()
    {
        $integral = Db('integral')->select();
        //
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
        $this->assign('integral',$integral);
        return $this->fetch();
    }

    /**
    ** 积分规则添加操作
    **/
    public function doIntegralAdd()
    {
        $flag = input('post.flag');
        $data['value'] = input('post.value');
        //
        $res = Db('integral')->where('flag',$flag)->update($data);
        if($res ==1){
            return $this->success('添加成功','admin/integralList');
        }else{
            return $this->error('添加失败');
        }
    
    }
    /**
    ** 积分规则的列表显示页面
    **/
    public function integralList()
    {
        $integral = Db('integral')
                ->select();
        $this->assign('integral',$integral);
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
        return $this->fetch();
    }

    /**
    *   积分的修改页面
    **/
    public function integralEdit()
    {
        $id = input('get.id');
        //
        $integral = Db('integral')->where('id',$id)->find();
        //
        $adminUser = Session::get('adminUser');
        //查询
        $integrals = Db('integral')
                ->select();
        $this->assign('adminUser',$adminUser);
        $this->assign('integral',$integral);
        $this->assign('integrals',$integrals);
        return $this->fetch();
    }
    
    /**
    **  积分规则修改操作
    **/
    public function doIntegralEdit()
    {
        $data['flag'] = input('post.flag');
        $data['value'] = input('post.value');
        $id = input('post.id');
        $res = Db('integral')->where('id',$id)->update($data);
        if($res ==1){
            return $this->success('更新成功','admin/integralList');
        }else{
            return $this->error('更新失败');
        }
    }


    /**
    **  积分日志列表
    **/
    public function integralLogList()
    {
        //设置缓存的key值
        $request = Request::instance();
        $key = $request->url(true);
         //判断缓存是否存在
         // if(!Cache::get($key)){
            $integralLog = Db('integral_log')
                ->order('addtime desc')
                ->order('id desc')
                ->paginate(10);
            //设置缓存
         //     Cache::set($key,$integralLog,3600);
         // }else{
         //     //读取缓存
         //     $integralLog = Cache::get($key);
         // }
         $adminUser = Session::get('adminUser');
         $this->assign('adminUser',$adminUser);
         $this->assign('integralLog',$integralLog);
         return $this->fetch();   
    }
    /**
    8*  积分日志的删除操作
    **/
    public function integralLogDelete()
    {
        $id = input('get.id');
        $res = Db('integral_log')->where('id',$id)->delete();
        if($res ==1){
            return $this->success('删除成功','admin/integralLogList');
        }else{
            return $this->error('删除失败');
        }
    }


    
    /********************************优惠券管理****************************************/
    /**
    **优惠券的添加页面
    **/
    public function couponAdd()
    {
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
        return $this->fetch(); 
    }
    /**
    * 优惠券的添加操作
    **/
    public function doCouponAdd()
    {
        $addTime1 = input('post.addtime1');
        $addTime2 = input('post.addtime2');
        $endTime1 = input('post.endtime1');
        $endTime2 = input('post.endtime2');
        $content = input('post.content');
        $addtime1 = isset($addTime1) ? $addTime1 : '';
        $addTime2 = isset($addTime2) ? $addTime2 : '';
        $endTime1 = isset($endTime1) ? $endTime1 : '';
        $endTime2 = isset($endTime2) ? $endTime2 : '';
        $content = isset($content) ? $content : '';
        //开始的时间
        $addTime = $addtime1.','.$addTime2;
        $addTime = strtotime($addTime);
        //结束的时间
        $endTime = $endTime1.','.$endTime2;
        $endTime = strtotime($endTime);       
        $data['addtime'] = $addTime;
        $data['endtime'] = $endTime;
        $data['content'] = $content;
        //插入数据
        $res = Db('coupon')->insert($data);
        if($res == 1){
            return $this->success('添加成功','admin/couponList');
        }else{
            return $this->error('添加失败');
        }
    }

    public function couponList()
    {
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
        //
        //设置缓存的key值
        $request = Request::instance();
        $key = $request->url(true);
         //判断缓存是否存在
         // if(!Cache::get($key)){
            $coupon = Db('coupon')
                ->order('addtime desc')
                ->order('id desc')
                ->paginate(10);
            //设置缓存
         //     Cache::set($key,$coupon,3600);
         // }else{
         //     //读取缓存
         //     $coupon = Cache::get($key);
         // }
        $this->assign('coupon',$coupon);
        return $this->fetch();
    }

    public function couponDelete()
    {
        $id = input('get.id');
        $res = Db('coupon')->where('id',$id)->delete();
        if($res ==1){
            return $this->success('删除成功','admin/couponList');
        }else{
            return $this->error('删除失败');
        }
    }

    /****************************************************/
     /**
    *  客户端添加页面
    **/
    public function versionAdd()
    {
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
        $addName = Db('app')->select();
        $this->assign('addName',$addName);
        return $this->fetch();
    }
    /**
    **  客户端的添加操作
    **/
    public function doVersionAdd()
    {
        $appId = input('post.pid');
        $versionCode = input('post.versionCode');
        $type = input('post.type');
        $versionContent = input('post.versionContent');
        if(empty($appId)){
            return $this->error('请选择客户端类型');
        }
        if(empty($versionCode)){
            return $this->error('请填写客户端版本号');
        }
        if(empty($type)){
            return $this->error('请选择是否强制更新');
        } 
        if(empty($versionContent)){
            return $this->error('请填写客户端版本描述');
        } 
        $data['app_id'] = $appId;
        $data['version_code'] = $versionCode;
        $data['type'] = $type; 
        $data['create_time'] = time();
        $data['version_content'] = $versionContent;    
        //接受文件
        $version = request()->file('version');
        //判断是否上传文件
        if(!empty($version)){
            // 移动到框架应用根目录/public/uploads/ 目录下
            $versioninfo = $version->move(ROOT_PATH . 'public' . DS . 'uploads/version');
            if($versioninfo){
                    $version = "/uploads/version/20".date("ymd",time())."/".$versioninfo->getBasename();
            } 
            $data['version_url'] = $version;
        }else{
            return $this->error('未上传客户端源码包');
        }
        $res = Db('version_upgrade')->insert($data);
        if($res ==1){
            return $this->success('添加成功','admin/versionList');
        }else{
            return $this->error('添加失败');
        }
    }

    /**
    * 客户的查看页面
    **/
    public function versionList()
    {
        //
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
        $version = Db('version_upgrade')
                ->order('app_id desc')
                ->order('version_code  desc')
                ->order('create_time desc')
                ->paginate(10);
        $this->assign('version',$version);
        return $this->fetch();
    }

    /**
    ** 客户端的删除操作
    **/
    public function versionDelete()
    {
        $id = input('get.id');
        $version = Db('version_upgrade')->where('id',$id)->find();
        if(file_exists(PATH.$version['version_url']) && is_file(PATH.$version['version_url'])){
            //删除原来的图片
            $result = unlink(PATH.$version['version_url']);
        }     
        $result = Db('version_upgrade')->where('id',$id)->delete();
        if($result == 1){
            return $this->success('删除成功','admin/versionList');
        }else{
            return $this->error('删除失败');
        }
    }
 /********************************直播管理****************************************/

    /*
    **创建直播流
    **/
    public function videoLiveAdd()
    {   
        // echo json_encode($aaa);
        vendor('pili-sdk-php#v2-master.lib.Pili_v2');
        $ak = "3i3ZvMKt8vafh38cAH8E6X0a0YrtAtojszFRHRPj";
        $sk = "FI9b2f4DeHVRSYoHKihOSUp-Sj17S7C0w885nzY5";
        $hubName = "yudong";

        //创建时间
        $time = Db('videolive')->select();
        // var_dump($time);die;
        //当前时间
        $ftime = time();

        $sql=Db::table('videolive')
        ->where('id',1)
        ->update(['ftime' => time()]);
        // var_dump($sql);exit;
 
        // var_dump($time[0]['time']);exit;
        if($ftime-$time[0]['time']>3600){

            //创建hub
            // echo "================Create hub\n";
            $mac = new \Qiniu\Pili\Mac($ak, $sk);
            $client = new \Qiniu\Pili\Client($mac);
            $hub = $client->hub($hubName);
            //获取stream
            // echo "================Get stream\n";
            $streamKey = "php-sdk-test" . time();
            $stream = $hub->stream($streamKey);

            try {
                //创建stream
                // echo "================Create stream\n";
                $resp = $hub->create($streamKey);
                // //获取stream info
                // echo "================Get stream info\n";
                $resp = $stream->info();
                // //列出所有流
                // echo "================List streams\n";
                $resp = $hub->listStreams("php-sdk-test", 1, "");
                // //列出正在直播的流
                // echo "================List live streams\n";
                $resp = $hub->listLiveStreams("php-sdk-test", 1, "");
            } catch (\Exception $e) {
                echo "Error:", $e, "\n";
            }

            //RTMP 推流地址
            $push = \Qiniu\Pili\RTMPPublishURL("pili-publish.www.zgyejy.net", $hubName, $streamKey, 3600, $ak, $sk);
            // RTMP 直播放址
            $pull = \Qiniu\Pili\RTMPPlayURL("pili-live-rtmp.www.zgyejy.net", $hubName, $streamKey);
            // HLS 直播地址
            $hls = \Qiniu\Pili\HLSPlayURL("pili-live-hls.www.zgyejy.net", $hubName, $streamKey);
            //HDL 直播地址
            $hdl = \Qiniu\Pili\HDLPlayURL("pili-live-hdl.www.zgyejy.net", $hubName, $streamKey);
            //截图直播地址
            $icon = \Qiniu\Pili\SnapshotPlayURL("pili-live-snapshot.www.zgyejy.net", $hubName, $streamKey);
            //插入语句
            
            if(empty($time)){
                $sql= Db('videolive')->insert(['push_url'=>$push,'pull_url'=>$pull,'hls_url'=>$hls,'hdl_url'=>$hdl,'icon_url'=>$icon,'time'=>$time,'ftime'=>$ftime]);

            }else{
                $sql= Db('videolive')->where('id',1)->update(['push_url'=>$push,'pull_url'=>$pull,'hls_url'=>$hls,'hdl_url'=>$hdl,'icon_url'=>$icon,'time'=>$time,'ftime'=>$ftime]);
                // echo 'aaa';
            }

            // var_dump($sql);

            $adminUser = Session::get('adminUser');
            $this->assign('adminUser',$adminUser);
            $this->assign('push',$push);
            $this->assign('pull',$pull);
            $this->assign('hls',$hls);
            $this->assign('hdl',$hdl);
            $this->assign('icon',$icon);

            $this->success('更新成功', 'videoLiveList');
            return $this->fetch();   

        }else{

            $video = Db('videolive')->select();
            $adminUser = Session::get('adminUser');
            $this->assign('adminUser',$adminUser);
            $this->assign('push',$video[0]['push_url']);
            $this->assign('pull',$video[0]['pull_url']);
            $this->assign('hls',$video[0]['hls_url']);
            $this->assign('hdl',$video[0]['hdl_url']);
            $this->assign('icon',$video[0]['icon_url']);

            $this->success('更新成功', 'videoLiveList');
            
            return $this->fetch();   

        }
        
    }

    /*
    **直播流列表
    **/
    public function videoLiveList()
    {   

        // $video = db('videolive')->select();
        // var_dump($video);die;
        $sql =Db::table('videolive')->field('id,push_url,pull_url,hls_url,hdl_url,icon_url')->where('id',1)->select();
        // var_dump($sql);die;
        
        $adminUser = Session::get('adminUser');
        // var_dump($adminUser);exit;
        $this->assign('adminUser',$adminUser);
        $this->assign('sql',$sql);


        return $this->fetch();

    }
    /*
    **直播流管理
    **/
    public function pullInfo()
    {   
        $sql =Db::table('videolive')->field('pull_url,hls_url,hdl_url,icon_url')->where('id',1)->select();
        $pull_url = $sql[0]['pull_url'];
        $hls_url = $sql[0]['hls_url'];
        $hdl_url =  $sql[0]['hdl_url'];
        $icon_url = $sql[0]['icon_url'];
        $arr = array('code'=>'200','message'=>'成功','pull_url'=>"$pull_url",'hls_url'=>"$hls_url",'hdl_url'=>"$hdl_url",'icon_url'=>"$icon_url");
        // return json_encode($arr);
        var_dump($arr);
    }
    /*
    **观看直播效果
    **/
    public function videoInto()
    {
        $id = input('get.id');
        $sql =Db::table('videolive')->field('id,pull_url,icon_url,hdl_url,hls_url')->where('id',1)->select();  

        // var_dump($sql);die;
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
        $this->assign('sql',$sql);
          
        return $this->fetch();

    }
    /*
    **秀一秀
    **/
    public function shows()
    {
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);


        $shows = Db::table('shows')
            ->field('id,uid,word,image,video,music,text,time')
            ->order('id asc')
            ->paginate(10);            

        $this->assign('shows',$shows);

        return $this->fetch();
    }

    /**
    * 管理员的删除操作
    **/
    public function showsDelete()
    {
        $id = input('get.id');
        $id = isset($id) ? $id : '';
        if(!empty($id)){
            $res = Db('shows')
                    ->where('id',$id)
                    ->delete();
            if($res == 1){
                return $this->success('删除成功');
            }else{
                return $this->error('删除失败');
            }
        }else{
            return $this->error('删除失败'); 
        }
        
    }





/**********************电子绘本*************************************************电子绘本***************************/
    /*
    **电子绘本 图片添加
    **/
    public function bookVideoAdd()
    {
        //当前用户明
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
        // $cates = Db::table('cates')->select();
        $cates = $this->getAllCates();
        $this->assign('cates',$cates);
        return $this->fetch();
    }
    /*
    **电子绘本 图片上传
    **/
    public function doBookVideoAdd()
    {
        //接受图片和视频
        $video_zip = request()->file("video_zip");
        // var_dump($video_zip);
        // echo "<br>";
        // $video = request()->file("video");     
        //判断是否上传图片
        foreach ($video_zip as $key => $value) {
            if(!empty($value)){
                $value = $this->uploadImg($value);
                $data['video_zip'] = $value;

                $data['video_name'] = input('post.video_name');
                $data['video_describe'] = input('post.video_describe');
                       
                $data['video_addtime'] = time();
                //浏览数量
                $data['see_num'] = 0;
                //评论数量
                $data['evaluate_num'] =0;
                //收藏数量
                $data['collect_num'] =0;
                //设置时间
                $data['set_time'] =input('post.set_time');
                //分类id
                $data['cate_id'] = input('post.cate_id');

            if($data['cate_id']){
                $cates = Db('cates')->where('id',$data['cate_id'])->find();
                $data['cate_name'] = $cates['name'];
                // var_dump($data['cate_name']);
            }  
                $data['video_style'] =0;
                $res = Db('bookvideo')->insert($data);
        		// var_dump($value);

            }
        }
        // die;

        if($res == 1){
            return $this->success('上传成功','admin/bookVideoList');
        }else{
            return $this->error('上传失败');
        }
    }

    /*
    **电子绘本列表 图片列表
    **/
    public function bookVideoList()
    {
         //当前用户明
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
        //创建缓存的键名
        $request = Request::instance();
        $key = $request->url(true);
        
        $video_style = input('get.video_style');
        $video_name = input('get.video_name');
         if(empty($video_style) && empty($video_name))
        {
            //判断是否有缓存
            // if(!Cache::get($key)){
                 $video = Db::table('bookvideo')
                        ->order('id desc')                               
                        ->paginate(10);
                //设置缓存
            //     Cache::set($key,$video,360);
            // }else{
            //     //获取缓存
            //     $video = Cache::get($key);
            // }
        }
        //
        if(!empty($video_name)){
            $video = Db::table('bookvideo')
                    ->order('id desc')
                    ->where('video_name','like','%'.$video_name.'%')
                    ->paginate(10);
        }
        //

        if(!empty($video_style)){
            $video = Db::table('bookvideo')
                    ->order('id desc')
                    ->where('video_style','=', $video_style)
                    ->paginate(10);
        }
        //
        if(!empty($video_style) && !empty($video_name))
        {
             $video = Db::table('bookvideo')
                    ->order('id desc')
                    ->where(function($query){
                            $query->where('video_style','=',$video_style);
                            $query->where('video_name','like','%'.$video_name.'%');
                    })                               
                ->paginate(10);
        }       
        $this->assign('video',$video);
        return $this->fetch();
    }
    /**
    **图片的修改页面
    **/
    public function bookVideoEdit()
    {
        //当前用户明
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
        $cates = $this->getAllCates();
        // var_dump($cates);
        $this->assign('cates',$cates);
        $video = Db::table('bookvideo')->where('id','=',input('get.id'))->find();
        //
        $this->assign('video',$video);
        //
        return $this->fetch();
    }
    /** 
    *   图片的修改操作
    **/
    public function doBookVideoEdit()
    {
        $videoinfo = Db::table('bookVideo')->where('id','=',input('post.id'))->find();
         //接受图片和视频
        $video_zip = request()->file("video_zip");
        // $video = request()->file("video");
       

        //判断是否修改图片
        if(!empty($video_zip)){
            //判断文件是否存在
            if(file_exists(PATH.$videoinfo['video_zip']) && is_file(PATH.$videoinfo['video_zip'])){
                //
                $result = unlink(PATH.$videoinfo['video_zip']);
                if(!$result){
                    return $this->error('修改失败');
                }
            } 
            //上传新图片
            $video_zip = $this->uploadimg($video_zip); 
            $data['video_zip'] = $video_zip;         
        }
        
        //判断是否上传图片
        // if(!empty($video)){
        //     //判断文件是否存在
        //     if(file_exists(PATH.$videoinfo['video_url']) && is_file(PATH.$videoinfo['video_url'])){
        //         //删除原来的视频
        //         $result = unlink(PATH.$videoinfo['video_url']);
        //         if(!$result){
        //             return $this->error('修改失败');
        //         }
        //     }
        //     //上传新视频
        //     $video = $this->uploadvideo($video);
        //     $data['video_url'] = $video;             
        // }
        
        
        //
        $video_name = input('post.video_name');
        if(!empty($video_name)){
            $data['video_name'] = $video_name;
        }
        //
        $video_describe = input('post.video_describe');
        if(!empty($video_describe)){
            $data['video_describe'] = $video_describe;
        }
        //
        // $video_price = input('post.video_price');
        // if(!empty($video_price)){
        //     $data['video_price'] = $video_price;
        // } 
        // //
        // $video_jifen = input('post.video_jifen');
        //  if(!empty($video_jifen)){
        //     $data['video_jifen'] = $video_jifen;
        // }       
        //        
        $data['video_addtime'] = time();
        //判断是否付费
        // $video_style = input('post.video_style');
        // if($video_style == 1){
        //     $data['video_style'] = '1';
        //     $data['video_price'] = '';
        //     $data['video_jifen'] = '';
        // }elseif($video_style == 2){
        //     $data['video_style'] = '2';
        //     $data['video_jifen'] = '';
        // }elseif($video_style == 3){
        //     $data['video_style'] = '3';
        //     $data['video_price'] = '';
        // }
        $data['set_time'] =input('post.set_time');
        
        $data['cate_id'] = input('post.cate_id');
        // var_dump($data['cateId']);die;
        if($data['cate_id']){
            $cates = Db('cates')->where('id',$data['cate_id'])->find();
            $data['cate_name'] = $cates['name'];
        }       
        //修改
        $res = Db::table('bookvideo')->where('id','=',input('post.id'))->update($data);
        if($res == 1){
            return $this->success('修改成功','admin/bookVideoList');
        }else{
            return $this->error('修改失败');
        }
    }


    /**
    *   视频的删除操作
    **/
    public function bookVideoDelete()
    {
        $id = input('get.id');
        $videoinfo = Db::table('bookvideo')->where('id','=',input('get.id'))->find();
        //判断视频是否存在
        if(file_exists(PATH.$videoinfo['video_url']) && is_file(PATH.$videoinfo['video_url'])){
                //删除原有文件
               $delViode = unlink(PATH.$videoinfo['video_url']);
        }
        //判断图片是否存在
        if(file_exists(PATH.$videoinfo['video_zip']) && is_file(PATH.$videoinfo['video_zip'])){
                //删除原有文件
                $delImg = unlink(PATH.$videoinfo['video_zip']);
        }
        
    //判断
        $res = Db::table('bookvideo')->where('id','=',input('get.id'))->delete();
        if($res == 1){
             return $this->success('删除成功','admin/bookVideoList');
        }else{
             return $this->error('删除失败');
        }         
    }





    /**
    ** mp3和文档添加页面
    **/
    public function bookMp3TextAdd()
    {
        //当前用户明
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
        $cates = $this->getAllCates();
        $this->assign('cates',$cates);
        return $this->fetch();
    }
    /**
    **mp3添加操作
    **/
    public function doBookMp3TextAdd()
    {
        $data['music_name'] = input('post.music_name');
        // var_dump($data['music_name']);
        // $data['text_name'] = input('post.text_name');
        // $data['text_price'] = input('post.text_price');
        // $data['text_jifen'] = input('post.text_jifen');
        //
        // $music_style = input('post.music_style');
        // var_dump($music_style);die;
        // if($music_style == 0 || empty($music_style)){
        //     return $this->error('mp3类型参数不合法123');
        // } 
        // $data['music_style'] = $music_style;
        //
        // $text_style = input('post.text_style');
        // if($text_style == 0 || empty($text_style)){
        //     return $this->error('mp3类型参数不合法');
        // } 

        //
        $music = request()->file("music");
        // var_dump($music);
        // $text = request()->file('text');
         //判断是否上传mp3
        if(!empty($music)){
            $music = $this->uploadMusic($music);
            $data['music'] = $music;

            $data['music_style'] = 0;
            $data['music_jifen'] = 0;
            $data['music_price'] = 0;     
        // var_dump($music);

        }
        //判断是否上传mp3
        // if(!empty($text)){
        //     $text = $this->uploadText($text);
        //     $data['text'] = $text;
        // }
        $data['cateId'] = input('post.cate_id');
        // var_dump($data['cateId']);
        if($data['cateId']){
            $cates = Db('cates')->where('id',$data['cateId'])->find();
            $data['cate_name'] = $cates['name'];
        }       
        $res = Db('bookmp3text')->insert($data);
        if($res == 1){
            return $this->success('上传成功','admin/bookMp3TextList');
        }else{
            return $this->error('上传失败');
        }
    }

    /**
    **mp3列表页
    **/
    public function bookMp3TextList()
    {
        //当前用户明
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
        $mp3Text = Db::table('bookMp3text')
                    ->order('id desc')
                    ->paginate(10); 
        
        // var_dump($mp3Text );die;
        // foreach($mp3Text as $k => $v){
        //   $mp3Text[$k]['cateId'] = $v['cateId'];
                
        // }                    
        $this->assign('mp3Text',$mp3Text);
        return $this->fetch();               
    }


    /**
    ** 修改页面
    **/
    public function bookMp3TextEdit()
    {
        //当前用户明
        $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
        $cates = $this->getAllCates();
        $this->assign('cates',$cates);
        $mp3Text = Db::table('bookMp3Text')->where('id','=',input('get.id'))->find();
        
        $this->assign('mp3Text',$mp3Text);

        return $this->fetch();
    }
    /**
    ** 修改操作
    **/
    public function doBookMp3TextEdit()
    {
        //判断是否修改mp3的参数
        $musicName = input('post.music_name');
        if(!empty($musicName)){
            $data['music_name'] = $musicName;
        }
        // $musicPrice = input('post.music_price');
        // if(!empty($musicPrice)){
        //     $data['music_price'] = $musicPrice;
        // }
        // //
        // $musicStyle = input('post.music_style');
        // if(!empty($musicStyle)){
        //         if($musicStyle == 1){
        //             $data['music_style'] = '1';
        //             $data['music_price'] = '';
        //             $data['music_jifen'] = '';
        //         }elseif($musicStyle == 2){
        //             $data['music_style'] = '2';
        //             $data['music_jifen'] = '';
        //         }elseif($musicStyle == 3){
        //             $data['music_style'] = '3';
        //             $data['music_price'] = '';
        //         }
        // }
        //  $musicJifen = input('post.music_jifen');
        // if(!empty($musicJifen)){
        //     $data['music_jifen'] = $musicJifen;
        // }
        // //判断是否修改text的参数
        // $textName = input('post.text_name');
        // if(!empty($textName)){
        //     $data['text_name'] = $textName;
        // }
        // $textPrice = input('post.text_price');
        // if(!empty($textPrice)){
        //     $data['text_price'] = $textPrice;
        // }
        // $textStyle = input('post.text_style');
        // if(!empty($textStyle)){
        //         if($textStyle == 1){
        //             $data['text_style'] = '1';
        //             $data['text_price'] = '';
        //             $data['text_jifen'] = '';
        //         }elseif($textStyle == 2){
        //             $data['text_style'] = '2';
        //             $data['text_jifen'] = '';
        //         }elseif($textStyle == 3){
        //             $data['text_style'] = '3';
        //             $data['text_price'] = '';
        //         }
        // }
        // $textJifen = input('post.text_jifen');
        // if(!empty($textJifen)){
        //     $data['text_jifen'] = $textJifen;
        // }
        //是否改变分类
        $cateId = input('post.cate_id');
        if(!empty($cateId)){
            $data['cateId'] = $cateId;
            $cates = Db('cates')->where('id',$cateId)->find();
            $data['cate_name'] = $cates['name'];
        } 
        //
        $music = request()->file("music");
        // $text = request()->file('text');
        $mp3text = Db::table('bookMp3Text')->where('id','=',input('post.id'))->find();
          //判断是否上传mp3
        if(!empty($music)){
            //判断文件是否存在
            if(file_exists(PATH.$mp3text['music']) && is_file(PATH.$mp3text['music'])){
                //删除原来的视频
                $result = unlink(PATH.$mp3text['music']);
                if(!$result){
                    return $this->error('修改失败');
                }
            }
            //上传新视频
            $music = $this->uploadMusic($music);
            $data['music'] = $music;             
        }
          //判断是否上传文档
        // if(!empty($text)){
        //     //判断文件是否存在
        //     if(file_exists(PATH.$mp3text['text']) && is_file(PATH.$mp3text['text'])){
        //         //删除原来的文档
        //         $result = unlink(PATH.$mp3text['text']);
        //         if(!$result){
        //             return $this->error('修改失败');
        //         }
        //     }
        //     //上传新文档
        //     $text = $this->uploadText($text);
        //     $data['text'] = $text;             
        // }
         //修改
        $res = Db::table('bookMp3Text')->where('id','=',input('post.id'))->update($data);
        if($res == 1){
            return $this->success('修改成功','admin/bookMp3TextList');
        }else{
            return $this->error('修改失败');
        }
    }

  /**
    ** 删除操作
    **/

    public function bookMp3TextDelete()
    {
        $mp3text = Db::table('bookmp3text')->where('id','=',input('get.id'))->find();
        //判断mp3是否存在
        if(file_exists(PATH.$mp3text['music']) && is_file(PATH.$mp3text['music'])){
                //删除原有文件
                $delMusic = unlink(PATH.$mp3text['music']);
        }
        // //判断文档是否存在
        // if(file_exists(PATH.$mp3text['text']) && is_file(PATH.$mp3text['text'])){
        //         //删除原有文件
        //         $delText = unlink(PATH.$mp3text['text']);
        // }
         //判断
            $res = Db::table('bookmp3text')->where('id','=',input('get.id'))->delete();

            if($res == 1){
                 return $this->success('删除成功','admin/bookmp3TextList');
            }else{
                 return $this->error('删除失败');
            }  
    }

    //循环插入
    // public function xunhuan()
    // {
    //     $users = Db('users')->limit(1300,1400)->select();
        
    //     foreach($users as $k => $v){
    //         $data = array(
    //             'uid' => $v['id'],
    //              'nickname' => 'zgyejy'.$v['phone'],
    //             );
    //         Db('userinfo')->insert($data);
    //     }
    // }

    //替换	
    // public function pi(){
        
    //     $users = Db::table('users')->select();

    //     foreach($users as $k => $v){
    //         $data = array(
    //             'token' => $v['token']
    //             );

    //     }
    //     // var_dump($data['token']);

    //     Db::execute("update users set token =replace(token,'\#','Q')");
    // }
    public function chatroomedit()
    {
        $chatRoom = Db('chat_room')->where('id',1)->find();
         $adminUser = Session::get('adminUser');
        $this->assign('adminUser',$adminUser);
        $this->assign('chatRoom',$chatRoom);
        return $this->fetch();
    }

    public function dochatroomedit()
    {
        $id = input('post.id');
        $name = input('post.name');
        $roomname = input('post.roomname');
        if($name == $roomname){
             return $this->error('暂未修改');
        }else{
            $res = Db('chat_room')->where('id',$id)->update(['chat_room_name' => $roomname]);
            if($res >0){
                    return $this->error('修改成功');
            }else{
                return $this->error('修改失败');
            }
        }

    }



}
